<template>
  <div class="dispatch-view">
    <div class="operation-bar">
      <t-space>
        <t-button @click="handleBatchDispatch" :disabled="!selectedRows.length">
          批量派单
        </t-button>
        <t-input
          v-model="searchKey"
          placeholder="请输入关键词搜索"
          clearable
          @enter="handleSearch"
        >
          <template #suffix-icon>
            <search-icon @click="handleSearch" />
          </template>
        </t-input>
      </t-space>
    </div>

    <t-table
      :data="tableData"
      :columns="columns"
      :row-key="rowKey"
      :selected-row-keys="selectedRowKeys"
      :loading="loading"
      hover
      selectOnRowClick
      @select-change="onSelectChange"
    >
      <template #operation="{ row }">
        <t-space>
          <t-button
            variant="text"
            theme="primary"
            @click="handleSingleDispatch(row)"
          >
            派单
          </t-button>
        </t-space>
      </template>
    </t-table>

    <t-pagination
      v-model:current="pagination.current"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      @change="onPageChange"
    />

    <!-- 派单弹窗组件 -->
    <DispatchModal
      v-model:visible="dispatchModal.visible"
      :data="dispatchModal.data"
      :mode="dispatchModal.mode"
      @success="onDispatchSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { SearchIcon } from 'tdesign-icons-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import type { PrimaryTableCol, TableRowData } from 'tdesign-vue-next';
import DispatchModal from '../components/DispatchModal.vue';

interface TableItem extends TableRowData {
  id: string;
  key: string;
  name: string;
  region: string;
  amount: number;
  status: number;
  createTime: string;
}

// 表格数据
const tableData = ref<TableItem[]>([]);
const loading = ref(false);
const selectedRowKeys = ref<string[]>([]);
const selectedRows = ref<TableItem[]>([]);
const searchKey = ref('');

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 派单弹窗状态
const dispatchModal = reactive({
  visible: false,
  data: [] as TableItem[],
  mode: 'single' as 'single' | 'batch'
});

// 表格列配置
const columns: PrimaryTableCol<TableItem>[] = [
  { colKey: 'row-select', type: 'multiple', width: 50 },
  { colKey: 'name', title: '名称', width: 200 },
  { colKey: 'region', title: '区域', width: 120 },
  { colKey: 'amount', title: '数量', width: 100 },
  { 
    colKey: 'status', 
    title: '状态', 
    width: 100,
    cell: ({ row }) => {
      const statusMap: Record<number, string> = {
        0: '待派单',
        1: '已派单',
        2: '已完成'
      };
      return statusMap[row.status] || '未知';
    }
  },
  { colKey: 'createTime', title: '创建时间', width: 160 },
  { colKey: 'operation', title: '操作', width: 100 }
];

const rowKey = 'id';

// 处理表格选择
const onSelectChange = (
  keys: string[],
  rows: TableItem[]
) => {
  selectedRowKeys.value = keys;
  selectedRows.value = rows;
};

// 处理单行派单
const handleSingleDispatch = (row: TableItem) => {
  dispatchModal.data = [row];
  dispatchModal.mode = 'single';
  dispatchModal.visible = true;
};

// 处理批量派单
const handleBatchDispatch = () => {
  if (selectedRows.value.length === 0) {
    MessagePlugin.warning('请选择需要派单的记录');
    return;
  }
  dispatchModal.data = selectedRows.value;
  dispatchModal.mode = 'batch';
  dispatchModal.visible = true;
};

// 派单成功回调
const onDispatchSuccess = async (result: {
  type: 'single' | 'batch';
  tasks: Array<{ warningId: string; name: string }>;
  dispatchInfo: any;
}) => {
  // 这里可以根据实际需求刷新表格数据
  await fetchTableData();
  // 清空选择
  selectedRowKeys.value = [];
  selectedRows.value = [];
  MessagePlugin.success(
    `${result.type === 'single' ? '派单' : '批量派单'}成功`
  );
};

// 搜索处理
const handleSearch = () => {
  pagination.current = 1;
  fetchTableData();
};

// 分页变化处理
const onPageChange = () => {
  fetchTableData();
};

// 获取表格数据
const fetchTableData = async () => {
  loading.value = true;
  try {
    // 这里替换为实际的 API 调用
    const response = await fetch('/api/dispatch/list', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        pageSize: pagination.pageSize,
        pageIndex: pagination.current,
        searchKey: searchKey.value,
      }),
    });
    const data = await response.json();
    tableData.value = data.list;
    pagination.total = data.total;
  } catch (error) {
    MessagePlugin.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 初始化加载数据
fetchTableData();
</script>

<style scoped>
.dispatch-view {
  padding: 20px;
}

.operation-bar {
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
}
</style> 